package com.wing.product.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.enterprise.feign.EnterpriseClient;
import com.wing.enterprise.product.model.entity.CabInventoryProduct;
import com.wing.enterprise.product.model.request.CabInventoryProductForm;
import com.wing.order.service.DynamicService;
import com.wing.product.dao.ProductDao;
import com.wing.product.model.entity.Product;
import com.wing.product.model.entity.ProductDetail;
import com.wing.product.model.request.ProductDto;
import com.wing.product.model.response.ProductVO;
import com.wing.productself.model.entity.ProductDetailSelf;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 产品-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class ProductServiceImpl extends ServiceImpl<ProductDao, Product> implements ProductService {
    @Autowired
    private ProductDetailService productDetailService;

    @Autowired
    private ProductBrandService productBrandService;

    @Autowired
    private ProductCategoryService productCategoryService;
    @Autowired
    private ProductCategoryExtService productCategoryExtService;
    @Autowired
    private ProductTypeService productTypeService;
    @Autowired
    private ProductUnitService productUnitService;
    @Autowired
    private DynamicService dynamicService;
    @Autowired
    private EnterpriseClient enterpriseClient;

    @Override
    public List<ProductVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<ProductVO> pageList4app(Page page, Map<String, Object> params) {
        List<ProductVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public ProductVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    @Transactional
    public void batchAddProduct(List<Product> productList) throws Exception {

        for(Product product : productList){

            //添加产品
            QueryWrapper<Product> productWrapper = new QueryWrapper<>();
            productWrapper.eq("product_code", product.getProductCode());
            List<Product> productDbList = this.list(productWrapper);
            if(productDbList.size() > 0){
                throw new BusinessException("产品编码已存在！");
            }

            List<ProductDetail> productDetailList = product.getProductDetailList();

            //判断SKU编号是否有重复
            List newList = productDetailList.stream().map(ProductDetail::getSkuCode).distinct().collect(Collectors.toList());
            if(newList.size() != productDetailList.size()){
                throw new BusinessException("产品SKU编码重复！");
            }

            ////判断商品条码是否有重复
            //newList = productDetailList.stream().map(ProductDetail::getBarcode).distinct().collect(Collectors.toList());
            //if(newList.size() != productDetailList.size()){
            //    throw new BusinessException("商品条码重复！");
            //}
            //
            ////判断商品规格是否有重复
            //newList = productDetailList.stream().map(ProductDetail::getSkuSpecValueNames).distinct().collect(Collectors.toList());
            //if(newList.size() != productDetailList.size()){
            //    throw new BusinessException("商品规格重复！");
            //}

            this.baseMapper.insert(product);

            for(ProductDetail productDetail : productDetailList){
                //监测skuCode是否存在，保证唯一
                QueryWrapper<ProductDetail> wrapper = new QueryWrapper<>();
                wrapper.eq("settled_company_id", product.getSettledCompanyId());
                wrapper.eq("sku_code", productDetail.getSkuCode());
                List<ProductDetail> productDetailDbList = productDetailService.list(wrapper);
                if(productDetailDbList.size() > 0){
                    throw new BusinessException("产品SKU编码已存在！");
                }
                ////监测商品条码是否存在，保证唯一
                //if(StringUtils.isNotBlank(productDetail.getBarcode())) {
                //    QueryWrapper<ProductDetail> barcodeWrapper = new QueryWrapper<>();
                //    barcodeWrapper.eq("settled_company_id", product.getSettledCompanyId());
                //    barcodeWrapper.eq("barcode", productDetail.getBarcode());
                //    productDetailDbList = productDetailService.list(barcodeWrapper);
                //    if (productDetailDbList.size() > 0) {
                //        throw new BusinessException("产品商品条码已存在！");
                //    }
                //}
                //
                //////监测商品规格值是否存在,保证唯一
                //if(StringUtils.isNotBlank(productDetail.getSkuSpecValueNames())) {
                //    QueryWrapper<ProductDetail> skuSpecValueWrapper = new QueryWrapper<>();
                //    skuSpecValueWrapper.eq("product_id", product.getId());
                //    skuSpecValueWrapper.eq("sku_spec_value_names", productDetail.getSkuSpecValueNames());
                //    productDetailDbList = productDetailService.list(skuSpecValueWrapper);
                //    if (productDetailDbList.size() > 0) {
                //        throw new BusinessException("产品商品规格已存在！");
                //    }
                //}

                productDetail.setProductId(product.getId());

                productDetail.setProductTypeId(product.getProductTypeId());
                productDetail.setProductCategoryId(product.getProductCategoryId());
                productDetail.setUnitId(product.getUnitId());
                productDetail.setBrandId(product.getBrandId());
                if(null != product.getPricingMethod()) {
                    if (product.getPricingMethod().getValue() == ProductDetail.PricingMethod.piece.getValue()) {
                        productDetail.setPricingMethod(ProductDetail.PricingMethod.piece);
                    } else if (product.getPricingMethod().getValue() == ProductDetail.PricingMethod.weight.getValue()) {
                        productDetail.setPricingMethod(ProductDetail.PricingMethod.weight);
                    }
                }
                productDetail.setInventoryUnitType(ProductDetail.InventoryUnitType.quantity);
                productDetailService.save(productDetail);

                CabInventoryProductForm cabInventoryProductForm = new CabInventoryProductForm();
                cabInventoryProductForm.setSkuId(productDetail.getId());
                cabInventoryProductForm.setSkuCode(productDetail.getSkuCode());
                cabInventoryProductForm.setQuantity(0);
                cabInventoryProductForm.setSkuType(0);
                cabInventoryProductForm.setType(CabInventoryProduct.Type.make);
                //0本地仓 1云仓
                cabInventoryProductForm.setSourceType(0);
                JsonResult jsonResult = enterpriseClient.addCabInventoryProduct(cabInventoryProductForm);
                if(null == jsonResult || jsonResult.getCode() != 200){
                    throw new BusinessException("生成库存数据失败");
                }
            }

        }
    }

    @Override
    public List<ProductDto> findAllProduct(Map<String, Object> params) {

        return baseMapper.findAllProduct(params);
    }

    @Override
    @Transactional
    public void batchAddCompactProduct(List<Product> productList) {
        //OUT:
        for(Product item : productList){
            //添加产品
            QueryWrapper<Product> wrapper = new QueryWrapper<>();
            wrapper.eq("product_code", item.getProductCode());
            List<Product> productDbList = this.list(wrapper);
            if(productDbList.size() > 0){
                throw new BusinessException("产品编码已存在！");
            }
            List<ProductDetail> productDetailList = item.getProductDetailList();
            //判断SKU编号是否有重复
//            List newList = productDetailList.stream().map(ProductDetail::getSkuCode).distinct().collect(Collectors.toList());
//            if(newList.size() != productDetailList.size()){
//                throw new BusinessException("产品SKU编码重复！");
//            }
            baseMapper.insert(item);
            for(ProductDetail productDetail : productDetailList){
                //监测skuCode是否存在，保证唯一
                ProductDetail productDetailDbList = productDetailService.getOne(new LambdaQueryWrapper<ProductDetail>()
                        .eq(ProductDetail::getSkuCode,productDetail.getSkuCode()));
                if(productDetailDbList!=null){
                    if(!productDetailDbList.getIsDeleted()){
                        //throw new BusinessException("产品SKU编码已存在！");
                        continue;
                    }else {
                        productDetailService.removeById(productDetailDbList.getId());
                        baseMapper.deleteById(productDetailDbList.getProductId());
                    }
                }
                productDetail.setProductId(item.getId());
                productDetail.setProductTypeId(item.getProductTypeId());
                productDetail.setProductCategoryId(item.getProductCategoryId());
                productDetail.setBrandId(item.getBrandId());
                productDetail.setOldSpecCode(productDetail.getSkuSpecValueNames());
                productDetail.setSkuName(item.getName());
                productDetail.setSimplify(1);
                productDetail.setInventoryUnitType(ProductDetail.InventoryUnitType.quantity);
                productDetail.setCreator(JwtUtils.getLoginUserId());
                productDetail.setUnitId(item.getUnitId());
                productDetailService.save(productDetail);
            }
        }
    }

    @Override
    @Transactional
    public void batchAddCompactProductDetail(List<ProductDetail> productDetailList) {
        for(ProductDetail productDetail : productDetailList){
            Product item = baseMapper.selectById(productDetail.getProductId());

            //监测skuCode是否存在，保证唯一
            ProductDetail productDetailDbList = productDetailService.getOne(new LambdaQueryWrapper<ProductDetail>()
                    .eq(ProductDetail::getSkuCode,productDetail.getSkuCode()));
            if(productDetailDbList!=null){
                if(!productDetailDbList.getIsDeleted()){
                    //throw new BusinessException("产品SKU编码已存在！");
                    continue;
                }else {
                    productDetailService.removeById(productDetailDbList.getId());
                    baseMapper.deleteById(productDetailDbList.getProductId());
                }
            }
            productDetail.setProductId(item.getId());
            productDetail.setProductTypeId(item.getProductTypeId());
            productDetail.setProductCategoryId(item.getProductCategoryId());
//            productDetail.setBrandId(item.getBrandId());
            productDetail.setOldSpecCode(productDetail.getSkuSpecValueNames());
//            productDetail.setSkuName(item.getName());
            productDetail.setSimplify(1);
            productDetail.setInventoryUnitType(ProductDetail.InventoryUnitType.quantity);
            productDetail.setCreator(JwtUtils.getLoginUserId());
//            productDetail.setUnitId(item.getUnitId());
            productDetailService.save(productDetail);
        }
    }

}
